<?php
class PassportModel extends AbstractModel
{
	public function __construct()
	{
		parent::__construct('users');
	}

	protected function _setFields()
	{
		return array(
			'AID',
			'UserName',
			'Password',
			'Salt',
			'Status',
			'CreateDate',
			'Remark'
		);
	}

	protected function _setPrimaryKeys()
	{
		return array(
			'AID'
		);
	}

	protected function _setAutoIncrementFields()
	{
		return array(
			'AID'
		);
	}

	protected function _setForeignKeyRelation()
	{
		return array();
	}

	public function getUserInfoByUid($uid, $fields = '*')
	{
	    $uid = intval($uid);
	    if(empty($uid)) return array();
	    $sql = "SELECT {$fields} FROM `{$this->_table}` WHERE `AID`={$uid}";
	    $slave = DB::getSlave('Passport');
	    return $slave->getRow($sql);
	}

    public function getUserInfoByUserName($username, $fields = '*')
	{
	    if(empty($username)) return array();
	    $sql = "SELECT {$fields} FROM `{$this->_table}` WHERE `UserName`='{$username}'";
	    $slave = DB::getSlave('Passport');
	    return $slave->getRow($sql);
	}

	public function addUser($data)
	{
	    $data = $this->_getFieldsData($data);
		$dbMaster = DB::getMaster();
	    $sql = "INSERT INTO `{$this->_table}`(`UserName`, `Password`, `Salt`, `Status`, `CreateDate`, `Remark`)
	    VALUES('{$data['UserName']}', '{$data['Password']}', '{$data['Salt']}', '{$data['Status']}', '{$data['CreateDate']}', '{$data['Remark']}')";
	    return $dbMaster->exec($sql);
	}
	
	public function isLogined()
	{
	    $uid = Functions::gpc(Config::getConfig('COOKIEPRE', 'Passport').'uid', 'c', 0);
	    if(empty($uid)) return false;
	    $userInfo = $this->getUserInfoByUid($uid);
	    if(empty($userInfo) || $userInfo['Status'] != 1) return false;
	    //数据库中获取用户信息
	    $username = $userInfo['UserName'];
	    $md5Password = $userInfo['Password'];
	    if($this->getToken($uid, $username, $md5Password) != Functions::gpc(Config::getConfig('COOKIEPRE', 'Passport').'token', 'c', ''))
	    {
	        return false;
	    }
	    return $uid;
	}
	
	public function loginCheck($username, $password)
	{
	    if(empty($username) || empty($password))return false;
	    $userInfo = $this->getUserInfoByUserName($username);
	    $md5passInfo = $this->getMd5Password($password, $userInfo['AID'], $userInfo['Salt']);
	    if($md5passInfo['md5Passwrod'] == $userInfo['Password'])
	    {
	        $this->setLoginCookie($userInfo['AID'], $username, $md5passInfo['md5Passwrod']);
	        return true;
	    }
	    return false;
	}
	
	public function checkUserName($userName)
	{
		if($this->getUserInfoByUserName($userName, 'AID'))
		{
			return false;
		}
		return true;
	}

	public function getMd5Password($password, $uid = 0, $salt = '')
	{
	    if(empty($password)) return false;
	    if(empty($salt) || strlen($salt) != 4)
	    {
	        $uid = intval($uid);
	        if(!empty($uid))
	        {
	            $userInfo = $this->getUserInfoByUid($uid);
	            $salt = $userInfo['Salt'];
	        }
	        else
	        {
	            $salt = rand(1111, 9999);
	        }
	    }
	    return array('md5Passwrod'=>md5(md5($password).$salt), 'salt'=>$salt);
	}
	
	private function setLoginCookie($uid, $username, $md5Password)
	{
	    setcookie(Config::getConfig('COOKIEPRE', 'Passport').'uid', $uid);
	    setcookie(Config::getConfig('COOKIEPRE', 'Passport').'token', 
	                $this->getToken($uid, $username, $md5Password));
	}
	
	private function getToken($uid, $username, $md5Password)
	{
	    return md5($md5Password.$uid.Config::getConfig('TOKEN_SALT', 'Passport').$username);
	}

	protected function _validationField($fieldName, $value) 
	{
		return true;
	}

	public function __destruct()
	{
		//echo 'account model destruct!';
	}
}